<!-- bing  工艺建模 新增编辑 -->
<template>
  <div class="mesTechnology-add">
    <div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane :label="$t('mesTechnology.baseInfo')" name="1">
          <div class="tabs-1">
            <ele-form v-model="formData" v-bind="formConfig" ref="formData">
              <template v-slot:form-btn>
                <div>
                  <el-button type="primary" @click="handleSubmit(formData)">{{
                    $t("ele-form.submitBtnText")
                  }}</el-button>
                  <el-button @click="goBack">{{ $t("common.back") }}</el-button>
                </div></template
              >
            </ele-form>
          </div>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('mesTechnology.proOrder')"
          name="2"
          v-if="type != '1'"
        >
          <div class="tabs-2">
            <div class="top-pack">
              <el-radio-group
                v-model="tabPosition"
                @change="handleClicktopTabs"
                style="margin-bottom: 30px;"
              >
                <el-radio-button
                  :key="i"
                  v-for="(ite, i) in topTabs"
                  :label="ite.code"
                  >{{
                    ite.name +
                    (ite.stu == 1
                      ? `(${$t("mesTechnology.enabling")})`
                      : ite.stu == 2
                      ? `(${$t("mesTechnology.deactivate")})`
                      : ` ${$t("mesTechnology.wait")}`)
                  }}</el-radio-button
                >
              </el-radio-group>

              <el-descriptions size="medium" class="margin-top" :column="3">
                <el-descriptions-item
                  :label="$t('mesTechnology.workingTime')"
                  v-if="rightBase.standardTime"
                  >{{ rightBase.standardTime }}</el-descriptions-item
                >
                <el-descriptions-item :label="$t('mesTechnology.technology')">{{
                  rightBase.technologyName
                }}</el-descriptions-item>
                <el-descriptions-item :label="$t('mesTechnology.version')">{{
                  rightBase.versionNumber
                }}</el-descriptions-item>
                <el-descriptions-item
                  :label="$t('mesTechnology.technologyDesc')"
                >
                  {{ rightBase.remark || $t("mesTechnology.none") }}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('common.status')">
                  <el-tag
                    type="success"
                    v-if="Number(rightBase.technologyStatus) == 1"
                    >{{ $t("mesTechnology.Starting") }}</el-tag
                  >
                  <el-tag
                    type="warning"
                    v-else-if="Number(rightBase.technologyStatus) == 2"
                    >{{ $t("mesTechnology.Deactivating") }}</el-tag
                  >
                  <el-tag type="info" v-else>{{
                    $t("mesTechnology.wait")
                  }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="btm-pack">
              <div class="left-pack">
                <div class="top">
                  <div class="tit">
                    <h3>{{ $t("mesTechnology.processSingSequence") }}</h3>
                    <div>
                      <el-tooltip
                        class="item"
                        effect="dark"
                        :content="$t('mesTechnology.addTech')"
                        placement="top-start"
                      >
                        <el-button
                          @click="isShowWorkingDialog()"
                          type="primary"
                          icon="el-icon-circle-plus-outline"
                          circle
                        ></el-button>
                      </el-tooltip>
                      <el-tooltip
                        class="item"
                        effect="dark"
                        :content="$t('mesTechnology.deleteTech')"
                        placement="top-start"
                      >
                        <el-button
                          @click="handDel()"
                          type="danger"
                          icon="el-icon-delete"
                          circle
                        ></el-button
                      ></el-tooltip>
                    </div>
                  </div>
                  <div class="radio">
                    <el-radio v-model="radio" label="0">{{
                      $t("mesTechnology.sequentialProcessing")
                    }}</el-radio>
                    <el-radio v-model="radio" label="1">{{
                      $t("mesTechnology.parallelProcessing")
                    }}</el-radio>
                  </div>
                  <div class="radio">
                    <el-radio v-model="radio" label="2">{{
                      $t("mesTechnology.sequentialBatch")
                    }}</el-radio>
                    <el-radio v-model="radio" label="3">{{
                      $t("mesTechnology.parallelBatch")
                    }}</el-radio>
                  </div>
                </div>

                <div class="content">
                  <vuedraggable
                    v-if="list.length > 0"
                    v-model="list"
                    animation="300"
                    :disabled="radio == '1'"
                  >
                    <transition-group>
                      <el-card
                        shadow="hover"
                        v-for="(item, i) in list"
                        :key="i"
                        class="item"
                        :class="groupIndex == item.code ? 'clickBg' : ''"
                      >
                        <div class="card-pack">
                          <!-- <el-button type="primary" circle>{{
                            i + 1
                          }}</el-button> -->
                          <div>
                            <p>{{ i + 1 }} -</p>
                            <p>{{ item.name }}</p>
                          </div>
                          <p class="icon" @click="goDetails(item, item.code)">
                            <i
                              v-if="groupIndex != item.code"
                              class="el-icon-arrow-right"
                            ></i>
                            <i v-else class="el-icon-arrow-down"></i>
                          </p>
                        </div>
                      </el-card>
                    </transition-group>
                  </vuedraggable>
                  <div v-else>
                    <el-empty
                      :description="$t('mesTechnology.noProcess')"
                    ></el-empty>
                  </div>
                </div>
                <div
                  class="bottom"
                  v-if="WorkingFormConfig.isShowSubmitBtn && list.length > 0"
                >
                  <el-button type="primary" @click="saveProcess()">{{
                    $t("mesTechnology.saveOrder")
                  }}</el-button>
                </div>
              </div>
              <div class="right-pack">
                <!-- <div>
                  <el-alert
                    :title="$t('mesTechnology.alertMsg')"
                    type="error"
                    :center="true"
                    :closable="false"
                  >
                  </el-alert>
                </div> -->
                <ele-form
                  v-if="groupIndex && list.length > 0"
                  v-model="WorkingFormData"
                  v-bind="WorkingFormConfig"
                  :request-fn="handleSubmitWorking"
                  @request-success="handleSuccessWorking"
                ></ele-form>
                <div v-else>
                  <el-empty
                    :description="$t('mesTechnology.noData')"
                  ></el-empty>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <BaseDialog ref="baseDialog" @response="resBaseDialog" />

    <WorkingDialog ref="workingDialog" @response="resWorkingDialog" />
  </div>
</template>

<script>
//例如：import 《组件名称》 from '《组件路径》';

import BaseDialog from "./baseDialog.vue";
import WorkingDialog from "./workingDialog.vue";
import { config } from "./addConfig";
import {
  historyList,
  detailList,
  saveProcess,
} from "@/api/process/mesTechnology";
import vuedraggable from "vuedraggable";
import { getProcessDetail } from "@/api/process/mesProcess";

export default {
  name: "",
  mixins: [config],
  //import引入的组件需要注入到对象中才能使用
  components: { BaseDialog, vuedraggable, WorkingDialog },
  data() {
    const _this = this;
    //这里存放数据
    return {
      groupIndex: 0,
      list: [], // 下面加工顺序
      tabPosition: "0",
      topTabs: [], //上面版本

      rightBase: {
        standardTime: $i18n.t('add.minutes'),
        technologyName: $i18n.t('add.coarseOpening'),
        versionNumber: "A05",
        remark: "",
        technologyStatus: "0",
      },
      activeName: "1", //tabs绑定数值
      type: 1, //1新增,2编辑, 3查看
      radio: "0", //加工顺序选择
      id: "", //主键
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    $route: {
      handler(news, old) {
        console.log(news);
        try {
          let { type, id } = news.query;
          this.activeName = type == "3" ? "2" : "1";
          let oldId = old?.id ?? "";
          this.type = type;
          if (id) {
            this.id = id;
            //编辑查看基础信息详情
            this.rowBaseDetail(id, () => {
              if (type == "3") {
                this.setactiveNameApi("2");
                this.activeName = "2";
                this.initTopTabs(1);
                this.disabledBool(true); //不可编辑
              } else {
                this.disabledBool(false);
              }
            });
          } else {
            this.disabledBool(false);
          }
        } catch (error) {
          this.$message.error($i18n.t("mesTechnology.errorMsg"));
        }
      },
      deep: true,
      immediate: true,
    },
  },
  //方法集合
  methods: {
    //是否显示按钮,是否可编辑  true:不可编辑,不显示按钮
    disabledBool(bool) {
      this.formConfig.disabled = bool;
      this.formConfig.isShowSubmitBtn = !bool;
      this.WorkingFormConfig.disabled = bool;
      this.WorkingFormConfig.isShowSubmitBtn = !bool;
    },
    // 保存生产顺序
    async saveProcess() {
      let dsf = this.list;
      let obj = {
        parentId: this.rightBase.id,
        serialType: this.radio,
        list: this.list.map((item, index) => {
          return {
            processId: item.processId,
            serialNumber: Number(index) + 1,
          };
        }),
      };
      let res = await saveProcess(obj);
      this.$message.success($i18n.t("mesTechnology.saveSeqSuccess"));
      this.setRightBase(this.tabPosition);
      this.WorkingFormData = {};
      this.groupIndex = 0;
    },
    async setRightBase(data) {
      let obj = this.topTabs.find((ite) => data == ite.code);
      this.rightBase = {
        ...obj,
      };

      // 工序列表
      let res = await detailList(obj.id);

      let list = res.data.result.map((item) => {
        return {
          ...item,
          code: item.processId,
          name: item.processName,
        };
      });
      if (list.length > 0) {
        this.radio = list[0].serialType + "";
        this.list = list;
      } else {
        this.radio = "0";
        this.list = [];
      }
    },

    initTopTabs(type) {
      if (this.activeName == 2 && type == 1) {
        if (this.topTabs.length > 0) {
          this.tabPosition =
            this.formData.versionNumber || this.topTabs[0].code;
          this.handleClicktopTabs(this.tabPosition);
        }
      }
    },

    async setactiveNameApi(type, id) {
      if (type == "2") {
        let res = await historyList({
          technologyCode: id || this.formData.technologyCode,
        });

        this.topTabs = res.data.result.map((ite) => {
          return {
            ...ite,
            stu: Number(ite.technologyStatus),
            code: ite.versionNumber,
            name: ite.versionNumber,
          };
        });

        this.activeName = type;
        this.initTopTabs(1);
      } else {
        this.activeName = type;
      }
    },
    //tabs 选择 基本信息 生产顺序
    handleClick(data) {
      let { index } = data;

      if (index == "1") {
        //点击第二个  生产顺序
        this.setactiveNameApi("2");
      } else {
      }
    }, //版本选择
    handleClicktopTabs(tab) {
      //  console.log(tab);
      this.setRightBase(tab);
    },

    async goDetails(data, index) {
      this.groupIndex = index;
      // debugger;
      let technologyCode = this.formData.technologyCode;
      let technologyName = this.formData.technologyName;
      let versionNumber = this.formData.versionNumber;

      let techdata = {
        id: data.processId,
        technologyCode: technologyCode,
        versionNumber: versionNumber,
      };

      let res = await getProcessDetail(techdata);
      const form = res.data.result || {};
      form.reportOrNot = form.reportOrNot ? form.reportOrNot : "1";
      this.WorkingFormData = Object.assign({}, form);
      this.WorkingFormData.techProcessId = data.id;
      // 是否是最后一道工序，如果是最后一道工序，是否报工和启动或者停用2个字段不允许修改
      const isLastProcess = this.list[this.list.length - 1].processId === data.processId;
      this.WorkingFormConfig['formDesc']['activeStatus']['disabled'] = isLastProcess || false;
      this.WorkingFormConfig['formDesc']['reportOrNot']['disabled'] = isLastProcess || false;
    },
    handDel() {
      let index = this.list.findIndex((item) => item.code == this.groupIndex);
      if (index != -1) {
        this.$confirm(
          $i18n.t("common.deleteSingle",{name:$i18n.t('mesTechnology.nameProcess')}),
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            type: "warning",
          }
        ).then(() => {
          this.list.splice(index, 1);
          this.groupIndex = 0;
        });
      } else {
        this.$message.warning(this.$t("mesTechnology.single"));
      }
    },
    goBack() {
      this.$router.push("/process/mesTechnology");
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="scss">
.mesTechnology-add {
  & > div {
    width: 100%;
    display: flex;
    justify-content: space-between;
    & > div {
      width: 100%;
    }
    .tabs-1 {
      width: 80%;
    }
    .tabs-2 {
      width: 100%;
      .top-pack {
        width: 98%;
        margin: 0 10px;
      }
      .btm-pack {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        box-sizing: border-box;
        border: 1px solid #e5e7eb;
        .left-pack {
          width: 30%;
          border-right: 1px solid #e5e7eb;
          padding-right: 24px;
          .top {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            .tit {
              display: flex;
              width: 100%;
              padding: 10px 10px;
              justify-content: space-between;
              h3 {
                padding-left: 10px;
              }
            }
            .radio {
              padding: 10px 10px;
              padding-top: 0px;
            }
          }
          .content {
            width: 100%;
            height: 42vh;
            overflow: auto;
            .clickBg {
              background: rgb(182, 179, 179);
            }
            .card-pack {
              cursor: move;
              display: flex;
              align-items: center;
              justify-content: space-between;
              & > div {
                padding: 0 20px;
                display: flex;
                align-items: center;
              }
              .icon {
                cursor: pointer !important;
                padding: 0 20px;
              }
            }
            /deep/.el-card__body {
              padding: 10px;
            }
          }
          .bottom {
            display: flex;
            justify-content: center;
            padding: 5px 0;
          }
        }
        .right-pack {
          width: 70%;
          margin: 0 10px;
        }
      }
    }
  }
}
</style>
